﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using intelliPaper.Model;
using System.Linq;
using System.Runtime.InteropServices;

namespace intelliSys.Management.Automation.Test
{
    /// <summary>
    /// Interaction logic for QuestionMgmt.xaml
    /// </summary>
    public partial class QuestionMgmt : Window
    {
        Storyboard shrink;
        Storyboard expand;
        Storyboard darken;
        System.Windows.Media.Effects.BlurEffect blurE = new System.Windows.Media.Effects.BlurEffect();
        public QuestionMgmt()
        {
            this.InitializeComponent();
            this.Loaded += new RoutedEventHandler(QuestionMgmt_Loaded);
            CommandType = WindowCommandType._UNSPECIFIED_;
            dialogueResult = WindowCommandResult._UNSPECIFIED_;
            WindowBehavior = WindowBehaviorCommand.DoNotCreateMore;
            this.Unloaded += new RoutedEventHandler(QuestionMgmt_Unloaded);
            // Insert code required on object creation below this point.
        }



        void QuestionMgmt_Unloaded(object sender, RoutedEventArgs e)
        {
            DocViewer.Dispose();
        }

        public WindowCommandType CommandType
        {
            get;
            set;
        }
        public WindowCommandResult DialogueResult
        {
            get
            {
                return dialogueResult;
            }
        }
        public WindowBehaviorCommand WindowBehavior
        {
            get;
            set;
        }

        [DllImport("user32.dll")]
        protected static extern int SetClipboardViewer(IntPtr hWndViewer);
        [DllImport("user32.dll")]
        protected static extern bool ChangeClipboardChain(IntPtr hWndResume, IntPtr hWndNext);

        WindowCommandResult dialogueResult;
        void QuestionMgmt_Loaded(object sender, RoutedEventArgs e)
        {
            SetClipboardViewer((new System.Windows.Interop.WindowInteropHelper(this)).Handle);
            shrink = Resources["Shrink"] as Storyboard;
            expand = Resources["Expand"] as Storyboard;
            darken = Resources["darken"] as Storyboard;
            darken.Completed += new EventHandler(darken_Completed);
            preview.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(preview_MouseLeftButtonDown);
            DocViewer.OnLoadCompleted += new EventHandler<DocumentViewerLoadStatus>(DocViewer_OnLoadCompleted);
            this.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(QuestionMgmt_MouseLeftButtonDown);

            validationLogics[0].FrameworkElement = BdyText;
            validationLogics[1].FrameworkElement = BdyText3;
            validationLogics[2].FrameworkElement = QuestionType;
            validationLogics[3].FrameworkElement = WrongAnswerList;
            validationLogics[4].FrameworkElement = CorrectAnswerList;
            validationLogics[5].FrameworkElement = KnowledgePointsList;
            System.Windows.Interop.HwndSource source = PresentationSource.FromVisual(this) as System.Windows.Interop.HwndSource;
            if (source != null)
            {
                source.AddHook(WndProc);
            }
            //validationLogics[6].FrameworkElement = QuestionEnabled;
        }
        protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr WPram, IntPtr LPram, ref bool handled)
        {
            switch (msg)
            {
                case 0x0308:
                    {
                        PasteOpenXMLButton_Click(null, null);
                        break;
                    }
                case 0x0002:
                    {
                        ChangeClipboardChain((new System.Windows.Interop.WindowInteropHelper(this)).Handle, LPram);
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            return IntPtr.Zero;

        }
        void DocViewer_OnLoadCompleted(object sender, DocumentViewerLoadStatus e)
        {
            this.Dispatcher.Invoke(new Action(() =>
                {
                    Message.ShutdownWaitingCurrent();
                    if (e.ex != null)
                    {
                        Message.Show(this, "发生错误", MessageType.Comfirm, e.ex.ToString(), "在生成预览过程中发生了错误");
                    }
                    else
                    {
                        tabCtrl.SelectedItem = preview;
                    }
                }));
        }

        void preview_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!preview.IsSelected)
            {
                //  Visual_Effects.Visibility = System.Windows.Visibility.Visible;
                //  darken.Begin();
                DocViewer.LoadAsync((this.DataContext as Question).QuestionBody);
                DocViewer.Attached = this.DataContext as Question;
                Message.Show(this, "请稍后", MessageType.Wait, "", "生成预览");
            }
        }

        void darken_Completed(object sender, EventArgs e)
        {
            DocViewer.LoadAsync(BdyText.OriginalText);
            LayoutRoot.Effect = blurE;
        }

        Grid lastFocus;
        private void Grid_GotFocus(object sender, RoutedEventArgs e)
        {
            if ((sender as Grid) == lastFocus)
            {
                lastFocus = sender as Grid;
                return;
            }
            else
                lastFocus = sender as Grid;
            (expand.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[1].Value = groupBox1.ActualHeight - 300;
            expand.Begin(sender as FrameworkElement);
        }

        private void Grid_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((sender as Grid) != lastFocus)
            {
                lastFocus = sender as Grid;
                return;
            }
            else
                lastFocus = null;
            (shrink.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[0].Value = groupBox1.ActualHeight - 300;
            shrink.Begin(sender as FrameworkElement);
        }

        private void QuestionMgmt_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (Cursor == Cursors.Help)
            {
                if (e.OriginalSource is Run)
                    Message.Show(this, "Help System", MessageType.Comfirm, "[CDATA] IS NULL", "关于" + (e.OriginalSource as Run).Text + "的帮助");
                else if (e.OriginalSource is TextBlock)
                    Message.Show(this, "Help System", MessageType.Comfirm, "[CDATA] IS NULL", "关于" + (e.OriginalSource as TextBlock).Text + "的帮助");
                else
                    Message.Show(this, "Help System", MessageType.Comfirm, "您的鼠标未落在帮助点上。通常，帮助点是显示在程序中的文字，它们不包含在以下内容中\n1)文本框\n2)按钮", "无法找到类型为" + e.OriginalSource.GetType().Name + "的帮助");
                return;
            }
            this.DragMove();
        }

        private void PasteOpenXMLButton_Click(object sender, RoutedEventArgs e)
        {
            //if (PasteOpenXMLButton.Content.ToString() == "粘贴智能标签")
            //{
            var interopData = "";
            try
            {
                interopData = Clipboard.GetData("intelliSys.Management.Automation.Test").ToString();
            }
            catch (NullReferenceException)
            {
                //Message.Show(this, "无法粘贴", MessageType.Comfirm, " 您必须使用与本程序兼容的OpenXML Word文档粘贴内容。请打开兼容的Word文档，然后按下CopyClipboard，再试一次。", "无法使用智能标签粘贴");
                preview.IsEnabled = false;
                return;
            }
            string orig;
            string displayed;
            BdyText.OpenXMLEnabled = true;
            Interop.OpenXMLInteropHelper.GetOpenParts(interopData, out orig, out displayed);
            //DO NOT CHECK 4 DULPLICATION.
            //if (DataRepository.Questions.Any<Question>(o =>
            //    {
            //        return o.Summary.Contains(displayed) || displayed.Contains(o.Summary);
            //    }))
            //{
            //    var result = Message.Show(this, "", MessageType.Comfirm | MessageType.Cancel, "题库中可能已经存在该题，要继续添加这道题吗？", "可能的重复");
            //    if ((result == MessageType.Cancel))
            //    {
            //        return;
            //    }
            //}
            BdyText.DisplayedTextWhileOpenXMLEnabled = displayed;
            (this.DataContext as Question).Summary = displayed;
            (this.DataContext as Question).QuestionBody = orig;
            (this.DataContext as Question).IsOpenXMLEnabled = true;
            BdyText.OriginalText = orig;
            preview.IsEnabled = true;
            //PasteOpenXMLButton.Content = "关闭智能标签";
            BdyText.IsReadOnly = true;
            //}
            //else
            //{
            //    PasteOpenXMLButton.Content = "粘贴智能标签";
            //    BdyText.Text = "";
            //    BdyText.OriginalText = null;
            //    BdyText.DisplayedTextWhileOpenXMLEnabled = null;
            //    BdyText.OpenXMLEnabled = false;
            //    // BdyText.Clear();
            //    preview.IsEnabled = false;
            //    DocViewer.Clear();
            //}
        }

        private void OnSiteHelp_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void OnSiteHelp_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var HelpEnabled = Cursor == Cursors.Help;
            if (HelpEnabled)
            {
                HelpIndicator.Text = "已关闭OnSite帮助";
                Cursor = Cursors.Arrow;
            }
            else
            {
                HelpIndicator.Text = "已开启OnSite帮助";
                Cursor = Cursors.Help;
            }
            // TODO: Add event handler implementation here.
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button butt = sender as Button;
            if (butt.Content.ToString() == "展开")
            {
                butt.Content = "收起";
                (expand.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[1].Value = groupBox1.ActualHeight - 300;
                expand.Begin(butt.Parent as Grid);
            }
            else
            {
                butt.Content = "展开";
                (shrink.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[0].Value = groupBox1.ActualHeight - 300;
                shrink.Begin(butt.Parent as Grid);
            }
        }

        private void Button_Click_KnowledgePointAdd(object sender, RoutedEventArgs e)
        {
            GenericList gl = new GenericList();
            gl.commandBox.SelectedIndex = 2;
            gl.commandBox.IsEnabled = false;
            gl.ListSelectionMode = SelectionMode.Extended;
            gl.ShowDialog();
            if (gl.DialogueResult == null)
            {
                return;
            }
            var knowledgePts = (gl.DialogueResult as System.Collections.IList).Cast<KnowledgePoint>();
            Question dtctx = this.DataContext as Question;
            foreach (KnowledgePoint kp in knowledgePts)
            {
                if (dtctx.KnowledgePoints.Any<KnowledgePoint>(o =>
                    {
                        return o.ID == kp.ID;
                    }))
                {
                    Message.Show(this, "重复值", MessageType.Comfirm, "知识点中已经含有该值。\n重复的值不会被重复添加。", "检测到重复的值");
                    continue;
                }
                else
                {
                    dtctx.KnowledgePoints.Add(kp);
                }
            }
            KnowledgePointsList.Items.Refresh();
        }

        private void Button_Click_KnowledgePointRemove(object sender, RoutedEventArgs e)
        {
            if (AskForListViewSelectionIfUnselected(KnowledgePointsList))
            {
                (tabCtrl.DataContext as intelliPaper.Model.Question).KnowledgePoints.Remove(KnowledgePointsList.SelectedItem as intelliPaper.Model.KnowledgePoint);
                KnowledgePointsList.Items.Refresh();
            }
        }
        private bool AskForListViewSelectionIfUnselected(ListBox lstvw)
        {
            if (lstvw.SelectedItem == null)
            {
                Message.Show(this, "No Item Selected", MessageType.Comfirm, "必须选择一项以便继续", "未选择内容");
                return false;
            }
            return true;
        }

        private void TrueAnswer_Add_Click(object sender, RoutedEventArgs e)
        {
            string s = MessagePrompt.ShowDialogue(this, "填入一个字符串作为正确答案").ToString();
            if ((tabCtrl.DataContext as intelliPaper.Model.Question).TrueAnswers.Contains(s))
            {
                Message.Show(this, "重复值", MessageType.Comfirm, "重复的值", "正确答案中已经含有该值");
                return;
            }
            (tabCtrl.DataContext as intelliPaper.Model.Question).TrueAnswers.Add(s);
            CorrectAnswerList.Items.Refresh();
        }

        private void TrueAnswer_Delete_Click(object sender, RoutedEventArgs e)
        {
            if (AskForListViewSelectionIfUnselected(CorrectAnswerList))
            {
                (tabCtrl.DataContext as intelliPaper.Model.Question).TrueAnswers.Remove(CorrectAnswerList.SelectedItem as string);
                CorrectAnswerList.Items.Refresh();
            }
        }

        private void WrongAnswer_Add_Click(object sender, RoutedEventArgs e)
        {
            string s = MessagePrompt.ShowDialogue(this, "填入一个字符串作为错误答案").ToString();
            if ((tabCtrl.DataContext as intelliPaper.Model.Question).ErrorAnswers.Contains(s))
            {
                Message.Show(this, "重复值", MessageType.Comfirm, "重复的值", "错误答案中已经含有该值");
                return;
            }
            (tabCtrl.DataContext as intelliPaper.Model.Question).ErrorAnswers.Add(s);
            WrongAnswerList.Items.Refresh();
        }

        private void WrongAnswer_Delete_Click(object sender, RoutedEventArgs e)
        {
            if (AskForListViewSelectionIfUnselected(WrongAnswerList))
            {
                (tabCtrl.DataContext as intelliPaper.Model.Question).ErrorAnswers.Remove(WrongAnswerList.SelectedItem as string);
                WrongAnswerList.Items.Refresh();
            }
        }

        private void CheckList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var item = CheckList.SelectedItem;
            if (item == null)
                return;
            var current = (item as ValidationLogic).FrameworkElement;
            while (current.Parent.GetType() != typeof(TabItem))
            {
                current = current.Parent as FrameworkElement;
            }
            if (current != null)
            {
                (current.Parent as TabItem).IsSelected = true;
            }
            (item as ValidationLogic).FrameworkElement.Focus();
        }

        static ValidationLogic[] validationLogics;
        static QuestionMgmt()
        {
            validationLogics = new ValidationLogic[]
            {
                new ValidationLogic()
                {
                  //  FrameworkElement=BdyText,
                    PreventContinue =true,
                    Summary = "空域",
                    Detail = "题干不可为空"
                },
                new ValidationLogic()
                {
                    //FrameworkElement = BdyText3,
                    PreventContinue = true,
                    Summary = "空域或错误格式",
                    Detail = "难度预设为非空[0,1]数值"
                },
                new ValidationLogic()
                {
                  //  FrameworkElement = QuestionType,
                    PreventContinue=true,
                    Summary="空域",
                    Detail="题型不可为空"
                },
                new ValidationLogic()
                {
              //      FrameworkElement = WrongAnswerList,
                    PreventContinue = true,
                    Summary = "空域",
                    Detail = "错误答案不可为空"
                },
                new ValidationLogic()
                {
                //     FrameworkElement = CorrectAnswerList,
                    PreventContinue = true,
                    Summary = "空域",
                    Detail = "参考答案不可为空"
                },
                new ValidationLogic()
                {
             //    FrameworkElement = KnowledgePointsList,
                    PreventContinue = true,
                    Summary = "空域",
                    Detail = "知识点不可为空"
                },
              //  new ValidationLogic()
              //  {
              ////      FrameworkElement=QuestionEnabled,
              //      PreventContinue=false,
              //      Summary = "小心！",
              //      Detail = "未勾选启用"
              //  },
            };
            validationLogics[0].ValidateMethod = new ValidationLogic.Validate(ValidationLogic.Non_EmptyLogic);
            validationLogics[2].ValidateMethod = new ValidationLogic.Validate(ValidationLogic.NonSelectedLogic);
            validationLogics[1].ValidateMethod = new ValidationLogic.Validate(ValidationLogic.Double01Range);
            validationLogics[3].ValidateMethod = validationLogics[4].ValidateMethod = validationLogics[5].ValidateMethod = new ValidationLogic.Validate(ValidationLogic.ListBoxEmptyLogic);
            //validationLogics[6].ValidateMethod = new ValidationLogic.Validate(ValidationLogic.UnCheckedNotice);
        }
        private void Comfirm_Click(object sender, RoutedEventArgs e)
        {
            CheckList.Items.Clear();
            int warning = 0;
            foreach (var validate in validationLogics)
            {
                if (validate.Detail == "错误答案不可为空" && (this.DataContext as Question).QuestionType != "选择题")
                {
                    continue;
                }
                if (!validate.ValidateMethod(validate.FrameworkElement))
                {
                    CheckList.Items.Add(validate);
                    if (!validate.PreventContinue)
                    {
                        warning++;
                    }
                }
            }
            if (CheckList.Items.Count - warning != 0)
            {
                Message.Show(this, "验证错误", MessageType.Comfirm, "此页存在一个或多个验证错误，在继续之前，您必须更正它们。\n通常，验证框出现在上一屏幕的左下角。", "验证错误阻止继续进行");
                return;
            }
            if (warning != 0)
            {
                var result = Message.Show(this, "验证错误", MessageType.Comfirm | MessageType.Cancel, "此页存在一个或多个验证警告，在继续之前，建议您更正它们。\n通常，验证框出现在上一屏幕的左下角。\n单击确定以继续，取消以返回", "验证警告可能导致意外后果");
                if (result != MessageType.Comfirm)
                {
                    return;
                }
            }
            //if (Message.Show(this, "CONFIRMINATION", MessageType.Comfirm | MessageType.Cancel, "This action will perform a data base write even if no properties are changed.\nWould you like to continue?", "ABOUT TO WRITE TO DATABASE") != MessageType.Comfirm)
            //{
            //    return;
            //}
            if (CommandType == WindowCommandType.CreateNew)
            {
                dialogueResult = WindowCommandResult.CreateNewSavingChanges;
            }
            else
            {
                dialogueResult = WindowCommandResult.OpenSavingChanges;
            }
            this.Close();
            WindowBehavior = WindowBehaviorCommand.DoNotCreateMore;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (CommandType == WindowCommandType.Open)
            {
                dialogueResult = WindowCommandResult.OpenDiscardingChanges;
            }
            else
            {
                dialogueResult = WindowCommandResult.CreateNewDiscardingChanges;
            }
            this.Close();
        }

        private void HistoryList_Add_Click(object sender, RoutedEventArgs e)
        {
            HistoryMessage hm = new HistoryMessage();
            if ((WindowCommandResult)AddHistoryMessage.ShowDialogue(this, hm) == WindowCommandResult.CreateNewDiscardingChanges)
            {
                return;
            }
            if ((this.DataContext as Question).HistoryMessages.Any<HistoryMessage>(any =>
            {
                return any.ErrorRate == hm.ErrorRate && any.RecordDate == hm.RecordDate;
            }))
            {
                Message.Show(this, "", MessageType.Comfirm, "已经包含该历史消息，该重复项不可添加。\n修改日期或错误率以继续", "包含重复项");
                return;
            }
            (this.DataContext as Question).HistoryMessages.Add(hm);
            HistoryList.Items.Refresh();
        }

        private void HistoryList_Remove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                (this.DataContext as Question).HistoryMessages.Remove(HistoryList.SelectedItem as HistoryMessage);
                HistoryList.Items.Refresh();
            }
            catch
            {
                Message.Show(this, "", MessageType.Comfirm, "选择一项以继续", "空选择");
            }
        }

        private void ComfirmAndContinue_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Comfirm_Click(null, null);
            WindowBehavior = WindowBehaviorCommand.CreateMore;
        }

        private void BdyText3_MouseEnter(object sender, MouseEventArgs e)
        {
            (sender as TextBox).Focus();
            (sender as TextBox).SelectAll();
        }

        private void StartWordInterop(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(System.IO.Directory.GetCurrentDirectory() + "\\intelliSys.Management.Automation.Test.Word.docx");
            }
            catch
            {
                Message.Show(this, "Not Found", MessageType.Comfirm, "Microsoft Word Add-In Not Found", "将intelliSys.Management.Automation.Test.Word.docx放置在该应用程序的同一文件下。\n若该文件已经丢失，请重新安装程序。");
            }
        }
    }
}